package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.SimpleTreeAdapter;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.utils.LocalSearch;
import com.isunland.managesystem.utils.MyArrayUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/5/17 15:12
 */

public class SimpleTreeListFragment<T> extends BaseListFragment
    implements SimpleTreeAdapter.CallBack {

  TextView mTvAddress;
  LinearLayout mLlAddress;
  /** 所有的 */
  private ArrayList<T> mListAll;
  /** 当前适配器的 */

  private ArrayList<T> mListTemp;
  /** 选中的item */
  private ArrayList<T> mListSelect;
  private SimpleTreeAdapter<T> mAdapter;
  private SimpleTreeListParams mParams;

  @Override public void initData() {
    super.initData();
    mParams = mBaseParams instanceof SimpleTreeListParams ? (SimpleTreeListParams) mBaseParams
        : new SimpleTreeListParams();
    //mList = new ArrayList<>();
    mListAll = new ArrayList<>();
    mListSelect = new ArrayList<>();
    mListTemp = new ArrayList<>();
    mAdapter = new SimpleTreeAdapter<>(mActivity, mListTemp, mParams, this);
    //setIsForbiddenVolley(true);//禁用volley
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom(mParams.getTitle());
    setListAdapter(mAdapter);
    //禁用下拉刷新
    getPullRefreshListView().setMode(PullToRefreshBase.Mode.DISABLED);
    mLlAddress = (LinearLayout) view.findViewById(R.id.ll_address);
    //noinspection deprecation
    mLlAddress.setBackgroundColor(getResources().getColor(R.color.white));
    mTvAddress = (TextView) view.findViewById(R.id.tv_address);
    //例如 / 中国/
    //mTvAddress.setText(MyStringUtil.connect(getString(R.string.slash), mCurrentParentName,
    //    getString(R.string.slash)));
    mLlAddress.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        if (mListSelect.size() < 2) return;
        //updateItem(mListSelect.get(mListSelect.size() - 2), false);
        updateItem(MyArrayUtil.get(mListSelect, mListSelect.size() - 2), false);
      }
    });
  }

  @Override public String getUrl() {
    return mParams.getUrl();
  }

  @Override public HashMap<String, String> getparameters() {
    return mParams.getParamsNotEmpty().getParams();
  }

  @SuppressWarnings("all") @Override public void resolveResponse(String json) {
    //区域测试数据.
    //String json = MyUtils.readAssetsFile(MyApplication.getAppContext(), "test.json");
    mListAll = (ArrayList<T>) new Gson().fromJson(json, mParams.getClassOriginal()).getRows();
    updateItem((T) mParams.getItem(), true);
  }

  private void updateItem(T pItem, boolean isNext) {
    if (pItem == null) return;
    ArrayList<T> result =
        getListByPid(mListAll, LocalSearch.getFieldValue(pItem, mParams.getChildField()));
    if (result == null || result.size() == 0) return;
    setAdapter(result);
    if (isNext) {
      MyArrayUtil.add(mListSelect, pItem);
    } else {
      MyArrayUtil.remove(mListSelect, mListSelect.size() - 1);
    }
    String innerTitle =
        MyStringUtil.joinStr(mListSelect, mParams.getTitleField(), getString(R.string.slash));
    String title =
        MyStringUtil.connect(getString(R.string.slash), innerTitle, getString(R.string.slash));
    if (title != null) title = title.replaceAll("//", getString(R.string.slash));//去重
    mTvAddress.setText(title);
    //if (result == null || result.size() == 0) {
    //  setResult();
    //}
  }

  //private String nextText(String original, String pName) {
  //  return MyStringUtil.connect(original, getString(R.string.slash), pName,
  //      getString(R.string.slash));
  //}

  //private String previousText(String original) {
  //
  //  original = MyStringUtil.substring(original, 0, original.length() - 1);//去掉/
  //  original = MyStringUtil.substring(original, 0,
  //      original.lastIndexOf(getString(R.string.slash)) + 1);//去掉/之后的数据.
  //  return original;
  //}

  private void setAdapter(ArrayList<T> result) {
    if (result == null || result.size() == 0) return;
    mListTemp.clear();
    mListTemp.addAll(result);
    mAdapter.setCheckedItem(null);
    mAdapter.notifyDataSetChanged();
  }

  private ArrayList<T> getListByPid(ArrayList<T> list, String pid) {
    if (list == null || list.size() == 0 || pid == null) return null;
    ArrayList<T> resultList = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
      if (MyStringUtil.equals(pid,
          LocalSearch.getFieldValue(list.get(i), mParams.getParentField()))) {
        resultList.add(list.get(i));
      }
    }
    return resultList;
  }

  @Override protected int setCustomLayoutId() {
    return R.layout.fragment_simple_tree;
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    T item = mAdapter.getItem(position - 1);
    if (item == null) return;
    updateItem(item, true);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_confirmtext, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.menu_item_confirm) {
      T select = mAdapter.getCheckedItem();
      if (select == null) {
        ToastUtil.show("请在当前页面下选择!");
        return false;
      }
      //限定了只能选择子节点
      if (SimpleTreeListParams.ONLY_CHILD == mParams.getSelectType() && isParent(select)) {
        ToastUtil.show("请选择具体类别!");
        return false;
      }
      mListSelect.add(select);
      setResult();
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

  private void setResult() {
    Intent intent = new Intent();

    T selectItem = MyArrayUtil.get(mListSelect, mListSelect.size() - 1);
    //noinspection unchecked
    mParams.setItem(selectItem);
    mParams.setFullName(MyStringUtil.joinStr(mListSelect, mParams.getTitleField(), ""));
    intent.putExtra(BaseFragment.EXTRA_PARAMS, mParams);
    mActivity.setResult(Activity.RESULT_OK, intent);
    ToastUtil.show(LocalSearch.getFieldValue(selectItem, mParams.getTitleField()));
    mActivity.finish();
  }

  @Override public void refresh() {
    getListView().invalidateViews();
  }

  public boolean isParent(T selectItem) {

    ArrayList<T> result =
        getListByPid(mListAll, LocalSearch.getFieldValue(selectItem, mParams.getChildField()));
    return result != null && result.size() != 0;
  }
}
